<template>
    <page-header-wrapper>
        <a-card :bordered="false" style="margin-bottom: 20px" title="搜索查询">
            <div class="table-page-search-wrapper">
                <a-form v-bind="queryFormItemLayout">
                    <a-row :gutter="20">
                        <a-col :md="8" :sm="24">
                            <a-form-item label="账号">
                                <div style="display: flex;align-items: center">
                                    <a-input v-model="queryParam.username"
                                             placeholder="请输入"/>
                                    <a-button style=" margin-left: 10px"
                                              type="primary" @click="onSearch">
                                        查询
                                    </a-button>
                                </div>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </a-card>
        <a-card :bordered="false">
            <div class="table-operator">
                <div>
                    <a-button icon="plus" type="primary" @click="handleAdd">添加</a-button>
                </div>
            </div>
            <a-table
                :columns="columns"
                :data-source="tableData"
                :loading="tableLoading"
                :pagination="pagination"
                :rowSelection="rowSelection"
                :scroll="{ x: '100%' }"
                childrenColumnName="departs"
                rowKey="id"
                @change="handleChange"
            >
       <span slot="header" slot-scope="text, record">
           <a-avatar v-if="record.img" :size="64" :src="record.img"/>
           <a-avatar v-else :size="64" icon="user"/>
        </span>
                <span slot="status" slot-scope="text, record">
          <a-switch v-model="record.status"
                    @change="(value) => handleChangeSwitch(value,record)"/>
        </span>
                <span slot="action" slot-scope="text, record">
          <template>
            <a-button type="link" @click="handleEditPassword(record)">修改密码</a-button>
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm cancel-text="否" ok-text="是" title="确认删除?"
                          @confirm="del(record)">
              <a-button type="link">删除</a-button>
            </a-popconfirm>
          </template>
        </span>
            </a-table>
        </a-card>
        <a-modal
            :confirmLoading="modalLoading.loading1"
            :title="modalTitle.title1"
            :visible="modalShow.show1"
            :width="640"
            @cancel="handleCancel"
            @ok="handleConfirm"
        >
            <a-form-model
                v-if="modalShow.show1"
                ref="ruleForm1"
                :model="modalForm.ruleForm1"
                :rules="modalRules.rules1"
                style="margin-bottom:20px"
                v-bind="formItemLayout"
            >
                <a-form-model-item v-if="!modalForm.ruleForm1.id" label="账号"
                                   prop="username">
                    <a-input v-model="modalForm.ruleForm1.username"
                             placeholder="请输入"></a-input>
                </a-form-model-item>
                <a-form-model-item v-if="!modalForm.ruleForm1.id" label="密码"
                                   prop="password">
                    <a-input v-model="modalForm.ruleForm1.password"
                             placeholder="请输入"></a-input>
                </a-form-model-item>
                <a-form-model-item label="角色" prop="roleId">
                    <a-select v-model="modalForm.ruleForm1.roleId" allowClear
                              placeholder="请选择">
                        <a-select-option
                            v-for="item in roleList"
                            :key="item.value"
                            :value="item.value"
                        >{{ item.name }}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="部门" prop="departId">
                    <a-select v-model="modalForm.ruleForm1.departId" allowClear
                              placeholder="请选择">
                        <a-select-option
                            v-for="item in departList"
                            :key="item.value"
                            :value="item.value"
                        >{{ item.name }}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="名称" prop="realname">
                    <a-input v-model="modalForm.ruleForm1.realname"
                             placeholder="请输入"></a-input>
                </a-form-model-item>
                <a-form-model-item label="性别" prop="sex">
                    <a-select v-model="modalForm.ruleForm1.sex" allowClear
                              placeholder="请选择">
                        <a-select-option
                            v-for="item in sexList"
                            :key="item.value"
                            :value="item.value"
                        >{{ item.name }}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="头像" prop="img">
                    <UploadImage :url="modalForm.ruleForm1.img"
                                 @change-url="(url) => modalForm.ruleForm1.img = url"></UploadImage>
                </a-form-model-item>
                <a-form-model-item label="联系方式" prop="mobile">
                    <a-input v-model="modalForm.ruleForm1.mobile"
                             placeholder="请输入"></a-input>
                </a-form-model-item>
            </a-form-model>
        </a-modal>
        <a-modal
            :confirmLoading="modalLoading.loading2"
            :title="modalTitle.title2"
            :visible="modalShow.show2"
            :width="640"
            @cancel="modalShow.show2 = false"
            @ok="handleConfirmPassword"
        >
            <a-form-model
                v-if="modalShow.show2"
                ref="ruleForm2"
                :model="modalForm.ruleForm2"
                :rules="modalRules.rules2"
                style="margin-bottom:20px"
                v-bind="formItemLayout"
            >
                <a-form-model-item label="新密码"
                                   prop="password">
                    <a-input v-model="modalForm.ruleForm2.password"
                             placeholder="请输入"></a-input>
                </a-form-model-item>

            </a-form-model>
        </a-modal>
    </page-header-wrapper>
</template>
<script>
import basic from '@/mixins/basic'
import {
    getUserPage,
    readUser,
    updateUser,
    updateUserStatus,
    updateUserPasswordByAdmin,
    addUser,
    delUser,
    getRoleList,
    getDepartIsNot,
} from '@/api/api'
import UploadImage from '@/components/uploadImage'

const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$/


export default {
    mixins: [basic],
    components: {UploadImage},
    data() {
        function validator(rule, value, callback) {
            if(!value) {
                callback(new Error('新密码不能为空！'))
            } else if (!reg.test(value)) {
                callback(new Error('密码必须8-16位且包含数字，大写字母，小写字母，特殊字符中的任意三种！'))
            } else {
                callback()
            }
        }
        return {
            request: {
                page: getUserPage, update: updateUser, add: addUser, delete: delUser
            },
            queryParam: {},
            resetQueryParam: {},
            columns: [
                {
                    title: '账号',
                    dataIndex: 'username'
                },
                {
                    title: '名称',
                    dataIndex: 'realname'
                },
                {
                    title: '头像',
                    dataIndex: 'img',
                    scopedSlots: {customRender: 'header'}
                },
                {
                    title: '角色',
                    dataIndex: 'title'
                },
                {
                    title: '所属部门',
                    dataIndex: 'depart'
                },
                {
                    title: '联系方式',
                    dataIndex: 'mobile'
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    scopedSlots: {customRender: 'status'}
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    width: 200,
                    fixed: 'right',
                    scopedSlots: {customRender: 'action'}
                }
            ],
            tableData: [],
            modalForm: {
                ruleForm1: {
                    id: undefined,
                    username: '',
                    password: '',
                    realname: '',
                    roleId: '',
                    departId: '',
                    img: '',
                    mobile: '',
                    sex: 0,
                    captcha: ''
                },
                ruleForm2: {
                    id: undefined,
                    username: '',
                    password: '',
                    captcha: ''
                }
            },
            modalResetForm: {
                ruleForm1: {
                    id: undefined,
                    username: '',
                    password: '',
                    realname: '',
                    roleId: '',
                    departId: '',
                    img: '',
                    mobile: '',
                    sex: 0,
                }
            },
            modalRules: {
                rules1: {
                    username: [{required: true, message: '输入不能为空'}],
                    password: [{required: true, validator}],
                    realname: [{required: true, message: '输入不能为空'}],
                    roleId: [{required: true, message: '选择不能为空'}],
                    departId: [{required: true, message: '选择不能为空'}],
                },
                rules2: {
                    password: [{required: true, validator}],
                }
            },
            roleList: [],
            departList: [],
            sexList: [
                {value: 0, name: '男'},
                {value: 1, name: '女'},
            ]
        }
    },
    async created() {
        const roleRes = await getRoleList()
        this.roleList = roleRes.map(el => {
            return {
                value: el.id,
                name: el.title
            }
        })
        const departRes = await getDepartIsNot({pageNo: 1, pageSize: 9999})
        this.departList = departRes.map(el => {
            return {
                value: el.id,
                name: el.depart
            }
        })
    },
    methods: {
        del(record, param) {
            const h = this.$createElement;
            const that = this
            this.handleDelete(record, {captcha: '' , ...param}).catch(err => {
                if(err && err.code == 999999) {
                    // this.refreshImgFun()
                    let pwd = ''
                    this.$info({
                        title: '请输入管理员密码！',
                        content: h('div', {}, [
                            h('a-input', {
                                on: {
                                    input(e) {
                                        pwd = e.target.value
                                    }
                                }
                            }),
                        ]),
                        onOk() {
                            that.del(record, {captcha: pwd})
                        },
                    });
                }
            })
        },
        formattData(data) {
            data.forEach(el => {
                el.status = el.status == 0
            })
            console.log('data', data)
        },
        handleChangeSwitch(value, record) {
            updateUserStatus({
                id: record.id,
                status: record.status ? 0 : 1
            })
                .then(res => {
                    this.$message.success('修改状态成功')
                })
                .catch(() => {
                    record.status = !record.status
                })
        },
        handleEdit(rowItem) {
            readUser(rowItem.id).then(res => {
                for (const key in this.modalForm.ruleForm1) {
                    this.modalForm.ruleForm1[key] = res[key]
                }
                    this.modalForm.ruleForm1['depart'] = res['depart']

                console.log('his.modalForm.ruleFor',this.modalForm.ruleForm1)
                this.modalTitle.title1 = '修改'
                this.modalShow.show1 = true
                this.departList.splice(this.departList.length - 1, 1)
                this.departList.push({
                  value: this.modalForm.ruleForm1.departId,
                  name: this.modalForm.ruleForm1.depart,
                  disabled: true
                })
            })
        },
        handleConfirm() {
            this.$refs.ruleForm1.validate((valid) => {
                if (valid) {
                    this.modalLoading.loading1 = true
                    let form = {
                        ...this.modalForm.ruleForm1,
                        status: this.modalForm.ruleForm1.status ? 0 : 1
                    }
                    this.request[this.modalForm.ruleForm1.id ? 'update' : 'add']({
                        ...form
                    }).then(res => {
                        this.$message.success(res.msg)
                        this.modalLoading.loading1 = false
                        this.onValidate('ruleForm1')
                        this.modalShow.show1 = false
                        this.onSearch()
                    }).catch(() => {
                        this.modalLoading.loading1 = false
                    })
                }
            })
        },
        handleEditPassword(rowItem) {
            readUser(rowItem.id).then(res => {
                for (const key in this.modalForm.ruleForm2) {
                    this.modalForm.ruleForm2[key] = res[key] || ""
                }
                this.modalTitle.title2 = '修改密码'
                this.modalShow.show2 = true
            })
        },
        handleConfirmPassword(param = {}) {
            const h = this.$createElement;
            console.log('[this.modalForm.ruleForm2]', JSON.stringify(this.modalForm.ruleForm2, null, 3))
            const that = this
            this.$refs.ruleForm2.validate((valid) => {
                if (valid) {
                    this.modalLoading.loading2 = true
                    updateUserPasswordByAdmin({
                        ...this.modalForm.ruleForm2,
                        ...param
                    }).then(res => {
                        this.$message.success(res.msg)
                        this.modalLoading.loading2 = false
                        this.onValidate('ruleForm2')
                        this.modalShow.show2 = false
                        this.onSearch()
                    }).catch((err) => {
                        if(err.code == 999999) {
                            // this.refreshImgFun()
                            let pwd = ''
                            this.$info({
                                title: '请输入管理员密码！',
                                content: h('div', {}, [
                                    h('a-input', {
                                        on: {
                                            input(e) {
                                                pwd = e.target.value
                                            }
                                        }
                                    }),
                                ]),
                                onOk() {
                                    that.handleConfirmPassword({captcha: pwd})
                                },
                            });
                        }
                        this.modalLoading.loading2 = false
                    })
                    
                }
            })
        }
    }
}
</script>
